package com.chao.yyks.modular.config.controller;

import com.alibaba.fastjson.JSONObject;
import com.chao.common.util.StrUtile;
import com.chao.common.util.exception.SysException;
import com.chao.common.util.log.Inter;
import com.chao.common.util.reaction.Reaction;
import com.chao.yyks.modular.config.service.FdfsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 附件上传
 * @author chao
 * @date 2020/9/29
 * 七牛
 */
@Slf4j
@RestController
@RequestMapping("/fdfs")
public class FileController {

    @Autowired
    private FdfsService fdfsService;

    /**
     * 上传附件
     */
    @Inter(value = "FILE_UPLOAD_01", grade = "1")
    @RequestMapping(method = RequestMethod.POST, value = "upload")
    public Reaction upload(@RequestParam("file") MultipartFile file) {
        return fdfsService.uploadFile(file);
    }

    /**
     * 上传附件
     */
    @Inter(value = "FILE_UPLOAD_02", grade = "1")
    @RequestMapping(method = RequestMethod.POST, value = "uploadFileBase64")
    public Reaction uploadFileBase64(@RequestBody JSONObject file) {
        log.info("上传文件:{}", file);
        if (!file.containsKey("base64")) {
            throw new SysException("缺少base64!");
        }
        if (!file.containsKey("fileName")) {
            throw new SysException("缺少文件名称!");
        }
        return fdfsService.uploadFileBase64(file.getString("base64"), file.getString("fileName"));
    }

    /**
     * 文件下载
     */
    @Inter(value = "FILE_DOWNLOAD_01", grade = "1")
    @RequestMapping(method = RequestMethod.POST, value = "downLoadFile")
    public void downLoadFile(HttpServletResponse response, @RequestBody JSONObject data) throws IOException {
        if (StrUtile.isEmpty(data.getString("fileId"))) {
            throw new SysException("文件id不能为空!");
        }
        fdfsService.downLoadFile(response, data.getString("fileId"));
    }

}
